package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.entity.vo.UserLoginVo;
import com.atguigu.gulimall.auth.entity.vo.UserRegisterVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-01-13-17:12
 */
@Controller
public class LoginController {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 若只起到发送请求，然后跳转到一个页面的操作
     * 可以使用 springMVC 的 viewController：将请求和页面映射过来（GulimallWebConfig）
     */

    private static final String registerRedirect = "http://auth.gulimall.com/register.html";
    private static final String loginRedirect = "http://auth.gulimall.com/login.html";
    private static final String indexRedirect = "http://gulimall.com";

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo,
                           BindingResult result,
                           RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(
                    FieldError::getField, FieldError::getDefaultMessage));

            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:" + registerRedirect;
        }

        //真正的注册。调用远程服务进行注册
        //1、TODO 校验手机验证码的操作
        //2、验证码通过后，调用远程注册服务
        R r = memberFeignService.register(vo);
        if (r.getCode() == 0) {
            //注册成功回到登录页
            return "redirect:" + loginRedirect;
        } else {
            //失败
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:" + registerRedirect;
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null){
            //没有登录
            return "login";
        } else {
            return "redirect:" + indexRedirect;
        }
    }

    @PostMapping("/login")
    public String login(@Valid UserLoginVo vo, RedirectAttributes redirectAttributes,
                        HttpSession session) {
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            //成功 共享session数据
            MemberResponseVo data = r.getData(new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);

            //前往首页
            return "redirect:" + indexRedirect;
        } else {
            //失败 记录错误后返回登录页
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:" + loginRedirect;
        }
    }
}
